import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _localeContext from "choerodon-ui/pro/lib/locale-context";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _map from "lodash/map";
import _isUndefined from "lodash/isUndefined";
import _isNumber from "lodash/isNumber";
import _isBoolean from "lodash/isBoolean";
import _forEach from "lodash/forEach";
import pathToRegexp from 'path-to-regexp';
import moment from 'moment';
import { getCurrentOrganizationId, getCurrentRole, getResponse, resolveRequire } from "../utils/utils";
import { getInitialActiveTabKey, getInitialTabData, persistMenuTabs, tabListen, getActiveTabMenuId } from "../utils/menuTab";
import intl from "../utils/intl";
import { getRouterData } from "../utils/router";
import { queryCount, queryMenu, queryPromptLocale, updateDefaultLanguage as _updateDefaultLanguage } from "../services/api";
import { getC7nLocale, getC7nProLocale, getCpaasUILocale } from "../services/localeApi";
import { endTrace as _endTrace, startTrace as _startTrace, getTraceStatus as _getTraceStatus } from "../services/traceLogService";
import { getDvaApp } from "../utils/iocUtils";
/**
 * 将原始的菜单数据转成 intl 的多语言格式
 * @param {object[]} menuData - 原始的请求菜单接口的数据
 * @param {object} menuLocaleIntl - 存储菜单的 localeIntl
 * @returns
 */

function parseMenuToLocaleIntl(menuData, menuLocaleIntl) {
  if (menuData) {
    menuData.forEach(function (menuItem) {
      // eslint-disable-next-line no-param-reassign
      menuLocaleIntl[menuItem.code] = menuItem.name;

      if (menuItem.subMenus) {
        parseMenuToLocaleIntl(menuItem.subMenus, menuLocaleIntl);
      }
    });
  }
}
/**
 * 获取打平的菜单
 * @param {object[]} menus - 已经处理过的有层级的菜单
 */


function getFlatMenuData(menus) {
  var keys = {};
  menus.forEach(function (item) {
    if (item.children) {
      keys[item.path] = _objectSpread({}, item);
      keys = _objectSpread(_objectSpread({}, keys), getFlatMenuData(item.children));
    } else {
      keys[item.path] = _objectSpread({}, item);
    }
  });
  return keys;
}

function parseMenuData(menus, parent) {
  var menuData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  menuData.forEach(function (item) {
    var menuItem = {
      // TODO: 菜单需要使用到的数据在这里赋值
      name: item.code,
      // 菜单的名字是多语言
      icon: item.icon,
      path: item.route || '',
      // oracle 数据库 没有返回 防止拼接时候 undefined
      id: item.id,
      parentId: item.parentId,
      quickIndex: item.quickIndex,
      type: item.type,
      title: item.name
    };

    if (parent) {
      parent.children = parent.children || []; // eslint-disable-line

      parent.children.push(menuItem);
    } else {
      menus.push(menuItem);
    }

    if (item.subMenus) {
      parseMenuData(menus, menuItem, item.subMenus);
    }
  });
}
/**
 * 初始化 所有菜单的叶子节点
 * @param {Object} menu
 * @param {Object[]} queryMenus
 */


function getMenuNodeList(menu) {
  var queryMenus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  for (var i = 0; i < menu.length; i++) {
    if (_isUndefined(menu[i].children)) {
      queryMenus.push(_objectSpread(_objectSpread({}, menu[i]), {}, {
        title: menu[i].name && intl.get(menu[i].name)
      }));
    } else {
      getMenuNodeList(menu[i].children, queryMenus);
    }
  }

  return queryMenus;
} // 存储 加载了哪些多语言, 还会存储 antd 的多语言


var localLangCache = {};

function getGlobalModalConfig(_ref) {
  var app = _ref.app,
      _ref$getWrapperRouter = _ref.getWrapperRouterData,
      getWrapperRouterData = _ref$getWrapperRouter === void 0 ? function (e) {
    return e;
  } : _ref$getWrapperRouter;
  return {
    namespace: 'global',
    state: {
      collapsed: false,
      menu: [],
      language: '',
      // 当前语言
      // language: 'dict',
      cpaasUILocale: {},
      // 组件的国际化
      supportLanguage: [],
      routerData: {},
      notices: [],
      announces: [],
      layoutLoading: false,
      count: 0,
      menuLeafNode: [],
      tabs: [],
      activeTabKey: '/workplace',
      traceLogInfo: {},
      // trace 数据
      traceStatus: false,
      // trace 状态
      traceGroupId: undefined,
      // trace id
      tabsIsInit: false,
      // menuTabs 初始化完成
      menuLoad: false,
      // 菜单加载完毕
      activeTabMenuId: undefined
    },
    effects: {
      /**
       * 首屏 预加载内容
       * 初始化语言和菜单数据
       */
      init: /*#__PURE__*/_regeneratorRuntime.mark(function init(_ref2, _ref3) {
        var _ref2$payload, organizationId, _ref2$payload$languag, language, call, put, all, promiseAllLocale, _yield$all, _yield$all2, promptLocale, safePromptLocale, loadLocales;

        return _regeneratorRuntime.wrap(function init$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _ref2$payload = _ref2.payload, organizationId = _ref2$payload.organizationId, _ref2$payload$languag = _ref2$payload.language, language = _ref2$payload$languag === void 0 ? 'dict' : _ref2$payload$languag;
                call = _ref3.call, put = _ref3.put, all = _ref3.all;
                // 第一次加载肯定是没有切换语言的
                localLangCache[language] = {};
                promiseAllLocale = [call(queryPromptLocale, organizationId, language, 'cpaas.common')];
                _context.next = 6;
                return all(promiseAllLocale);

              case 6:
                _yield$all = _context.sent;
                _yield$all2 = _slicedToArray(_yield$all, 1);
                promptLocale = _yield$all2[0];
                safePromptLocale = getResponse(promptLocale);
                loadLocales = intl && intl.options && intl.options.locales || {}; // 设置或切换 当前intl的语言

                intl.init({
                  currentLocale: language,
                  locales: loadLocales,
                  warningHandler: function
                    /* e */
                  warningHandler() {// todo
                    // console.warn(e);
                  }
                });
                intl.load(_defineProperty({}, language, safePromptLocale));
                _context.next = 15;
                return put({
                  type: 'loadUILocale',
                  payload: {
                    language: language
                  }
                });

              case 15:
                _context.next = 17;
                return put({
                  type: 'initMenuTabs'
                });

              case 17:
                // tab 初始化完成后才进入 menuTab 处理流程
                tabListen();

              case 18:
              case "end":
                return _context.stop();
            }
          }
        }, init);
      }),
      lazyInit: /*#__PURE__*/_regeneratorRuntime.mark(function lazyInit(_ref4, _ref5) {
        var _ref4$payload, organizationId, _ref4$payload$languag, language, call, put, all, _yield$all3, _yield$all4, supportLanguage, safeSupportLanguage, list, menuListRes, menuList, menuLocaleIntl, menus, menuData, routerConfig, routerData, queryMenus;

        return _regeneratorRuntime.wrap(function lazyInit$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _ref4$payload = _ref4.payload, organizationId = _ref4$payload.organizationId, _ref4$payload$languag = _ref4$payload.language, language = _ref4$payload$languag === void 0 ? 'dict' : _ref4$payload$languag;
                call = _ref5.call, put = _ref5.put, all = _ref5.all;
                _context2.next = 4;
                return all([// 获取角色列表, 角色切换用到
                put({
                  type: 'user/fetchRoleList',
                  payload: {
                    organizationId: organizationId
                  }
                }) // 获取动态表格数据
                ]);

              case 4:
                _yield$all3 = _context2.sent;
                _yield$all4 = _slicedToArray(_yield$all3, 1);
                supportLanguage = _yield$all4[0];
                safeSupportLanguage = getResponse(supportLanguage);
                list = [];
                _context2.next = 11;
                return call(queryMenu, {
                  lang: language
                });

              case 11:
                menuListRes = _context2.sent;
                menuList = getResponse(menuListRes);
                menuLocaleIntl = {};
                parseMenuToLocaleIntl(menuList, menuLocaleIntl);
                parseMenuData(list, null, menuList || []);
                menus = list;
                parseMenuToLocaleIntl(menuList, menuLocaleIntl);
                intl.load(_defineProperty({}, language, menuLocaleIntl));
                menuData = getFlatMenuData(menus);
                routerConfig = getWrapperRouterData(app || getDvaApp());
                routerData = {}; // The route matches the menu

                Object.keys(routerConfig).forEach(function (path) {
                  // Regular match item name
                  // eg.  router /user/:id === /user/chen
                  var pathRegexp = pathToRegexp(path);
                  var menuKey = Object.keys(menuData).find(function (key) {
                    return pathRegexp.test("".concat(key));
                  });
                  var menuItem = {}; // If menuKey is not empty

                  if (menuKey) {
                    menuItem = menuData[menuKey];
                  }

                  var router = routerConfig[path]; // If you need to configure complex parameter routing,
                  // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
                  // eg . /list/:type/user/info/:id

                  router = _objectSpread(_objectSpread({}, router), {}, {
                    name: router.name || menuItem.name,
                    // tab 用到的数据
                    pathRegexp: pathRegexp,
                    title: router.title || menuItem.name,
                    icon: router.icon || menuItem.icon,
                    closable: _isBoolean(router.closable) ? router.closable : true,
                    path: path,
                    // tab 用到的数据
                    authority: router.authority || menuItem.authority,
                    hideInBreadcrumb: router.hideInBreadcrumb || menuItem.hideInBreadcrumb
                  });
                  routerData[path] = router;
                });
                queryMenus = getMenuNodeList(menus, []);
                _context2.next = 26;
                return put({
                  type: 'updateState',
                  payload: {
                    routerData: routerData,
                    language: language,
                    menu: menus,
                    menuLeafNode: queryMenus,
                    supportLanguage: safeSupportLanguage,
                    // 菜单加载完毕
                    menuLoad: true
                  }
                });

              case 26:
              case "end":
                return _context2.stop();
            }
          }
        }, lazyInit);
      }),
      fetchCount: /*#__PURE__*/_regeneratorRuntime.mark(function fetchCount(_, _ref6) {
        var call, put, data, unreadMessageCount;
        return _regeneratorRuntime.wrap(function fetchCount$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                call = _ref6.call, put = _ref6.put;
                _context3.next = 3;
                return call(queryCount);

              case 3:
                data = _context3.sent;

                if (!(data && _isNumber(data.unreadMessageCount))) {
                  _context3.next = 8;
                  break;
                }

                unreadMessageCount = data.unreadMessageCount;
                _context3.next = 8;
                return put({
                  type: 'saveNotices',
                  payload: {
                    count: unreadMessageCount
                  }
                });

              case 8:
              case "end":
                return _context3.stop();
            }
          }
        }, fetchCount);
      }),
      changeLanguage: /*#__PURE__*/_regeneratorRuntime.mark(function changeLanguage(_ref7, _ref8) {
        var payload, put, language, organizationId, roleId;
        return _regeneratorRuntime.wrap(function changeLanguage$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                payload = _ref7.payload;
                put = _ref8.put;
                language = payload;
                organizationId = getCurrentOrganizationId();
                roleId = getCurrentRole().id;
                _context4.next = 7;
                return put({
                  type: 'updateLocale',
                  payload: {
                    language: language,
                    roleId: roleId,
                    organizationId: organizationId
                  }
                });

              case 7:
              case "end":
                return _context4.stop();
            }
          }
        }, changeLanguage);
      }),

      /**
       * 更新国际化
       * antdLocale, C7nUILocale, commonLocale, menuLocale
       */
      updateLocale: /*#__PURE__*/_regeneratorRuntime.mark(function updateLocale(_ref9, _ref10) {
        var payload, call, put, all, _payload$language, language, organizationId, _yield$all5, _yield$all6, promptLocale, menuData, safePromptLocale, safeMenuData, safeMenuLocale, loadLocales, _loadLocales, updateState;

        return _regeneratorRuntime.wrap(function updateLocale$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                payload = _ref9.payload;
                call = _ref10.call, put = _ref10.put, all = _ref10.all;
                // 角色id是必须的
                _payload$language = payload.language, language = _payload$language === void 0 ? 'dict' : _payload$language, organizationId = payload.organizationId;

                if (localLangCache[language]) {
                  _context5.next = 24;
                  break;
                }

                localLangCache[language] = {};
                _context5.next = 7;
                return all([call(queryPromptLocale, organizationId, language, 'cpaas.common'), call(queryMenu, {
                  lang: language
                })]);

              case 7:
                _yield$all5 = _context5.sent;
                _yield$all6 = _slicedToArray(_yield$all5, 2);
                promptLocale = _yield$all6[0];
                menuData = _yield$all6[1];
                safePromptLocale = getResponse(promptLocale);
                safeMenuData = getResponse(menuData);
                safeMenuLocale = {};
                parseMenuToLocaleIntl(safeMenuData, safeMenuLocale); // 设置或切换 当前intl的语言

                loadLocales = intl && intl.options && intl.options.locales || {};
                intl.init({
                  currentLocale: language,
                  locales: loadLocales,
                  warningHandler: function
                    /* e */
                  warningHandler() {// todo
                    // console.warn(e);
                  }
                });
                intl.load(_defineProperty({}, language, _objectSpread(_objectSpread({}, safePromptLocale), safeMenuLocale)));
                _context5.next = 20;
                return put({
                  type: 'updateMenuLeafNode'
                });

              case 20:
                _context5.next = 22;
                return put({
                  type: 'updateState',
                  payload: {
                    language: language
                  }
                });

              case 22:
                _context5.next = 31;
                break;

              case 24:
                // 设置或切换 当前intl的语言
                _loadLocales = intl && intl.options && intl.options.locales || {};
                intl.init({
                  currentLocale: language,
                  locales: _loadLocales,
                  warningHandler: function
                    /* e */
                  warningHandler() {// todo
                    // console.warn(e);
                  }
                });
                updateState = {
                  language: language
                };
                _context5.next = 29;
                return put({
                  type: 'updateMenuLeafNode'
                });

              case 29:
                _context5.next = 31;
                return put({
                  type: 'updateState',
                  payload: updateState
                });

              case 31:
                _context5.next = 33;
                return put({
                  type: 'loadUILocale',
                  payload: {
                    language: language
                  }
                });

              case 33:
              case "end":
                return _context5.stop();
            }
          }
        }, updateLocale);
      }),

      /**
       * 加载 UI 的多语言
       */
      loadUILocale: /*#__PURE__*/_regeneratorRuntime.mark(function loadUILocale(_ref11, _ref12) {
        var language, call, put, all, c7nLocale, c7nProLocale, cpaasUILocale, _ref13, promiseAllLocale, _yield$all7, _yield$all8;

        return _regeneratorRuntime.wrap(function loadUILocale$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                language = _ref11.payload.language;
                call = _ref12.call, put = _ref12.put, all = _ref12.all;

                if (!(localLangCache[language] && localLangCache[language].c7nLocale)) {
                  _context6.next = 9;
                  break;
                }

                _ref13 = [localLangCache[language].c7nLocale, localLangCache[language].c7nProLocale, localLangCache[language].cpaasUILocale];
                c7nLocale = _ref13[0];
                c7nProLocale = _ref13[1];
                cpaasUILocale = _ref13[2];
                _context6.next = 20;
                break;

              case 9:
                promiseAllLocale = [call(getC7nLocale, language), call(getC7nProLocale, language), call(getCpaasUILocale, language)];
                _context6.next = 12;
                return all(promiseAllLocale);

              case 12:
                _yield$all7 = _context6.sent;
                _yield$all8 = _slicedToArray(_yield$all7, 3);
                c7nLocale = _yield$all8[0];
                c7nProLocale = _yield$all8[1];
                cpaasUILocale = _yield$all8[2];
                localLangCache[language].c7nLocale = c7nLocale;
                localLangCache[language].c7nProLocale = c7nProLocale;
                localLangCache[language].cpaasUILocale = c7nProLocale;

              case 20:
                _localeContext.setLocale(resolveRequire(c7nProLocale));

                if (cpaasUILocale) {
                  // 保证一定有antd的语言，没有可能是调用了多次 updateLocale
                  moment.locale(cpaasUILocale.locale); // TODO: LocaleProvider 中会设置 moment.locale，为何突然不起作用了?
                }

                _context6.next = 24;
                return put({
                  type: 'updateState',
                  payload: {
                    c7nLocale: c7nLocale,
                    cpaasUILocale: cpaasUILocale
                  }
                });

              case 24:
              case "end":
                return _context6.stop();
            }
          }
        }, loadUILocale);
      }),
      updateDefaultLanguage: /*#__PURE__*/_regeneratorRuntime.mark(function updateDefaultLanguage(_ref14, _ref15) {
        var payload, call, res;
        return _regeneratorRuntime.wrap(function updateDefaultLanguage$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                payload = _ref14.payload;
                call = _ref15.call;
                _context7.next = 4;
                return call(_updateDefaultLanguage, payload);

              case 4:
                res = _context7.sent;
                return _context7.abrupt("return", getResponse(res));

              case 6:
              case "end":
                return _context7.stop();
            }
          }
        }, updateDefaultLanguage);
      }),
      clearNotices: /*#__PURE__*/_regeneratorRuntime.mark(function clearNotices(_ref16, _ref17) {
        var payload, put, select, count;
        return _regeneratorRuntime.wrap(function clearNotices$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                payload = _ref16.payload;
                put = _ref17.put, select = _ref17.select;
                _context8.next = 4;
                return put({
                  type: 'saveClearedNotices',
                  payload: payload
                });

              case 4:
                _context8.next = 6;
                return select(function (state) {
                  return state.global.notices.length;
                });

              case 6:
                count = _context8.sent;
                _context8.next = 9;
                return put({
                  type: 'user/changeNotifyCount',
                  payload: count
                });

              case 9:
              case "end":
                return _context8.stop();
            }
          }
        }, clearNotices);
      }),
      removeTab: /*#__PURE__*/_regeneratorRuntime.mark(function removeTab(_ref18, _ref19) {
        var payload, put, select, state, tabs, activeTabKey, activeKey, lastIndex, panes, activeTabMenuId;
        return _regeneratorRuntime.wrap(function removeTab$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                payload = _ref18.payload;
                put = _ref19.put, select = _ref19.select;
                _context9.next = 4;
                return select(function (st) {
                  return st.global;
                });

              case 4:
                state = _context9.sent;
                tabs = state.tabs, activeTabKey = state.activeTabKey;
                activeKey = activeTabKey;
                tabs.forEach(function (pane, i) {
                  if (pane.key === payload) {
                    lastIndex = i - 1;
                  }
                });
                panes = tabs.filter(function (pane) {
                  return pane.key !== payload;
                });

                if (lastIndex >= 0 && activeTabKey === payload) {
                  activeKey = panes[lastIndex].key;
                }

                activeTabMenuId = getActiveTabMenuId(activeKey);
                _context9.next = 13;
                return put({
                  type: 'updateState',
                  payload: {
                    // openTab 会更新 activeTabKey, 并且需要用到之前的 activeTabKey 来判断需不需要 push。
                    // activeTabKey: activeKey,
                    tabs: _toConsumableArray(panes),
                    activeTabMenuId: activeTabMenuId.id
                  }
                });

              case 13:
                return _context9.abrupt("return", activeKey);

              case 14:
              case "end":
                return _context9.stop();
            }
          }
        }, removeTab);
      }),
      // 关闭其他tab 返回下一个激活的 activeKey
      removeOtherMenuTab: /*#__PURE__*/_regeneratorRuntime.mark(function removeOtherMenuTab(_ref20, _ref21) {
        var payload, put, select, state, tabs, tab, activeTabMenuId;
        return _regeneratorRuntime.wrap(function removeOtherMenuTab$(_context10) {
          while (1) {
            switch (_context10.prev = _context10.next) {
              case 0:
                payload = _ref20.payload;
                put = _ref21.put, select = _ref21.select;
                _context10.next = 4;
                return select(function (st) {
                  return st.global;
                });

              case 4:
                state = _context10.sent;
                tabs = state.tabs;
                tab = payload.tab;
                activeTabMenuId = getActiveTabMenuId(tab.key);
                _context10.next = 10;
                return put({
                  type: 'updateState',
                  payload: {
                    // openTab 会更新 activeTabKey, 并且需要用到之前的 activeTabKey 来判断需不需要 push。
                    // activeTabKey: tab.key,
                    tabs: tabs.filter(function (t) {
                      return t.key === tab.key || !t.closable;
                    }),
                    activeTabMenuId: activeTabMenuId.id
                  }
                });

              case 10:
                return _context10.abrupt("return", tab.key);

              case 11:
              case "end":
                return _context10.stop();
            }
          }
        }, removeOtherMenuTab);
      }),
      // 关闭其他tab 返回下一个激活的 activeKey
      removeSomeMenuTab: /*#__PURE__*/_regeneratorRuntime.mark(function removeSomeMenuTab(_ref22, _ref23) {
        var payload, put, select, state, tabs, removeTabs;
        return _regeneratorRuntime.wrap(function removeSomeMenuTab$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                payload = _ref22.payload;
                put = _ref23.put, select = _ref23.select;
                _context11.next = 4;
                return select(function (st) {
                  return st.global;
                });

              case 4:
                state = _context11.sent;
                tabs = state.tabs;
                removeTabs = payload.removeTabs;
                _context11.next = 9;
                return put({
                  type: 'updateState',
                  payload: {
                    tabs: tabs.filter(function (t) {
                      return !removeTabs.includes(t.key) || !t.closable;
                    })
                  }
                });

              case 9:
              case "end":
                return _context11.stop();
            }
          }
        }, removeSomeMenuTab);
      }),
      // 关闭所有tab 返回下一个激活的 activeKey
      removeAllMenuTab: /*#__PURE__*/_regeneratorRuntime.mark(function removeAllMenuTab(_ref24, _ref25) {
        var payload, put, select, state, tabs, tab, closestTab1, closestTab2, nextTabs, activeTabMenuId;
        return _regeneratorRuntime.wrap(function removeAllMenuTab$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                payload = _ref24.payload;
                put = _ref25.put, select = _ref25.select;
                _context12.next = 4;
                return select(function (st) {
                  return st.global;
                });

              case 4:
                state = _context12.sent;
                tabs = state.tabs;
                tab = payload.tab;
                // 记录左距离最近的 不可关闭的Tab
                nextTabs = tabs.filter(function (t) {
                  if (t.key === tab.key) {
                    if (!t.closable) {
                      // 如果该Tab不可关闭, 那么该Tab为下一个打开的Tab
                      closestTab2 = t;
                    } else {
                      // 如果该Tab可关闭, 那么新的Tab为之前最近的不可关闭的Tab
                      closestTab2 = closestTab1;
                    }
                  }

                  if (t.closable) {
                    return false;
                  }

                  closestTab1 = t;
                  return true;
                });
                activeTabMenuId = getActiveTabMenuId(closestTab2 || closestTab1 || {
                  key: '/'
                }.key);
                _context12.next = 11;
                return put({
                  type: 'updateState',
                  payload: {
                    // 至少会有工作台tab 所有不对 nextTabs 做空判断
                    // openTab 会更新 activeTabKey, 并且需要用到之前的 activeTabKey 来判断需不需要 push。
                    // activeTabKey: closestTab2.key,
                    activeTabMenuId: activeTabMenuId.id,
                    tabs: nextTabs
                  }
                });

              case 11:
                return _context12.abrupt("return", (closestTab2 || closestTab1 || {
                  key: '/'
                }).key);

              case 12:
              case "end":
                return _context12.stop();
            }
          }
        }, removeAllMenuTab);
      }),
      getRemoveTabInfo: /*#__PURE__*/_regeneratorRuntime.mark(function getRemoveTabInfo(_ref26, _ref27) {
        var payload, select, state, tabs, activeTabKey, closeTabKey, removeTabInfo, isNextTabKeyNeedSet;
        return _regeneratorRuntime.wrap(function getRemoveTabInfo$(_context13) {
          while (1) {
            switch (_context13.prev = _context13.next) {
              case 0:
                payload = _ref26.payload;
                select = _ref27.select;
                _context13.next = 4;
                return select(function (st) {
                  return st.global;
                });

              case 4:
                state = _context13.sent;
                tabs = state.tabs, activeTabKey = state.activeTabKey;
                closeTabKey = payload;
                removeTabInfo = {
                  nextTabs: [],
                  nextActiveTabKey: ''
                };
                isNextTabKeyNeedSet = activeTabKey === closeTabKey;

                _forEach(tabs, function (tab) {
                  if (tab.key !== closeTabKey) {
                    removeTabInfo.nextTabs.push(tab);

                    if (isNextTabKeyNeedSet) {
                      removeTabInfo.nextActiveTabKey = tab.key;
                      removeTabInfo.nextTab = tab;
                    }
                  } else {
                    isNextTabKeyNeedSet = false;
                  }
                });

                return _context13.abrupt("return", removeTabInfo);

              case 11:
              case "end":
                return _context13.stop();
            }
          }
        }, getRemoveTabInfo);
      }),

      /**
       * pubLayout 预加载
       * 首屏 预加载内容
       * 初始化语言和菜单数据
       */
      pubInit: /*#__PURE__*/_regeneratorRuntime.mark(function pubInit(_ref28, _ref29) {
        var _ref28$payload, _ref28$payload$langua, language, organizationId, call, put, all, promiseAllLocale, _yield$all9, _yield$all10, promptLocale, safePromptLocale, loadLocales;

        return _regeneratorRuntime.wrap(function pubInit$(_context14) {
          while (1) {
            switch (_context14.prev = _context14.next) {
              case 0:
                _ref28$payload = _ref28.payload, _ref28$payload$langua = _ref28$payload.language, language = _ref28$payload$langua === void 0 ? 'dict' : _ref28$payload$langua, organizationId = _ref28$payload.organizationId;
                call = _ref29.call, put = _ref29.put, all = _ref29.all;
                // 第一次加载肯定是没有切换语言的
                localLangCache[language] = {};
                promiseAllLocale = [call(queryPromptLocale, organizationId, language, 'cpaas.common')];
                _context14.next = 6;
                return all(promiseAllLocale);

              case 6:
                _yield$all9 = _context14.sent;
                _yield$all10 = _slicedToArray(_yield$all9, 1);
                promptLocale = _yield$all10[0];
                safePromptLocale = getResponse(promptLocale); // 设置或切换 当前intl的语言

                loadLocales = intl && intl.options && intl.options.locales || {};
                intl.init({
                  currentLocale: language,
                  locales: loadLocales,
                  warningHandler: function
                    /* e */
                  warningHandler() {// todo
                    // console.warn(e);
                  }
                });
                intl.load(_defineProperty({}, language, safePromptLocale));
                _context14.next = 15;
                return put({
                  type: 'loadUILocale',
                  payload: {
                    language: language
                  }
                });

              case 15:
              case "end":
                return _context14.stop();
            }
          }
        }, pubInit);
      }),

      /**
       * 用于 pubLayout 的懒加载
       */
      pubLazyInit: /*#__PURE__*/_regeneratorRuntime.mark(function pubLazyInit(_ref30, _ref31) {
        var language, put, routerConfig, routerData;
        return _regeneratorRuntime.wrap(function pubLazyInit$(_context15) {
          while (1) {
            switch (_context15.prev = _context15.next) {
              case 0:
                language = _ref30.payload.language;
                put = _ref31.put;
                // 获取动态表格数据
                routerConfig = getWrapperRouterData(app || getDvaApp());
                routerData = {}; // The route matches the menu

                Object.keys(routerConfig).forEach(function (path) {
                  // Regular match item name
                  // eg.  router /user/:id === /user/chen
                  var pathRegexp = pathToRegexp(path);
                  var router = routerConfig[path]; // If you need to configure complex parameter routing,
                  // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
                  // eg . /list/:type/user/info/:id

                  router = _objectSpread(_objectSpread({}, router), {}, {
                    name: router.name,
                    // tab 用到的数据
                    pathRegexp: pathRegexp,
                    title: router.title,
                    icon: router.icon,
                    closable: _isBoolean(router.closable) ? router.closable : true,
                    path: path,
                    // tab 用到的数据
                    authority: router.authority
                  });
                  routerData[path] = router;
                }); // 初始化 menuTabs

                _context15.next = 7;
                return put({
                  type: 'initMenuTabs'
                });

              case 7:
                // tab 初始化完成后才进入 menuTab 处理流程
                tabListen();
                _context15.next = 10;
                return put({
                  type: 'updateState',
                  payload: {
                    routerData: routerData,
                    language: language,
                    // TabListen 监听
                    menuLoad: true
                  }
                });

              case 10:
              case "end":
                return _context15.stop();
            }
          }
        }, pubLazyInit);
      }),

      /**
       * 用于 publicLayout 的懒加载
       */
      publicLazyInit: /*#__PURE__*/_regeneratorRuntime.mark(function publicLazyInit(_, _ref32) {
        var put, routerConfig, routerData;
        return _regeneratorRuntime.wrap(function publicLazyInit$(_context16) {
          while (1) {
            switch (_context16.prev = _context16.next) {
              case 0:
                put = _ref32.put;
                // 获取动态表格数据
                routerConfig = getWrapperRouterData(app || getDvaApp());
                routerData = {}; // The route matches the menu

                Object.keys(routerConfig).forEach(function (path) {
                  // Regular match item name
                  // eg.  router /user/:id === /user/chen
                  var pathRegexp = pathToRegexp(path);
                  var router = routerConfig[path]; // If you need to configure complex parameter routing,
                  // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
                  // eg . /list/:type/user/info/:id

                  router = _objectSpread(_objectSpread({}, router), {}, {
                    name: router.name,
                    // tab 用到的数据
                    pathRegexp: pathRegexp,
                    title: router.title,
                    icon: router.icon,
                    closable: _isBoolean(router.closable) ? router.closable : true,
                    path: path,
                    // tab 用到的数据
                    authority: router.authority
                  });
                  routerData[path] = router;
                });
                _context16.next = 6;
                return put({
                  type: 'updateState',
                  payload: {
                    routerData: routerData,
                    // TabListen 监听
                    menuLoad: true,
                    tabsIsInit: true
                  }
                });

              case 6:
              case "end":
                return _context16.stop();
            }
          }
        }, publicLazyInit);
      }),
      publicLayoutLanguage: /*#__PURE__*/_regeneratorRuntime.mark(function publicLayoutLanguage(_ref33, _ref34) {
        var _ref33$payload$langua, language, put, loadLocales;

        return _regeneratorRuntime.wrap(function publicLayoutLanguage$(_context17) {
          while (1) {
            switch (_context17.prev = _context17.next) {
              case 0:
                _ref33$payload$langua = _ref33.payload.language, language = _ref33$payload$langua === void 0 ? 'dict' : _ref33$payload$langua;
                put = _ref34.put;
                loadLocales = intl && intl.options && intl.options.locales || {}; // 设置或切换 当前intl的语言

                intl.init({
                  currentLocale: language,
                  locales: loadLocales
                });
                _context17.next = 6;
                return put({
                  type: 'updateState',
                  payload: {
                    language: language
                  }
                });

              case 6:
              case "end":
                return _context17.stop();
            }
          }
        }, publicLayoutLanguage);
      }),

      /**
       * 用于 privateLayout 的懒加载
       */
      privateLazyInit: /*#__PURE__*/_regeneratorRuntime.mark(function privateLazyInit(_ref35, _ref36) {
        var _ref35$payload, _ref35$payload$langua, language, organizationId, call, put, all, routerConfig, routerData, promiseAllLocale, _yield$all11, _yield$all12, promptLocale, safePromptLocale, loadLocales;

        return _regeneratorRuntime.wrap(function privateLazyInit$(_context18) {
          while (1) {
            switch (_context18.prev = _context18.next) {
              case 0:
                _ref35$payload = _ref35.payload, _ref35$payload$langua = _ref35$payload.language, language = _ref35$payload$langua === void 0 ? 'dict' : _ref35$payload$langua, organizationId = _ref35$payload.organizationId;
                call = _ref36.call, put = _ref36.put, all = _ref36.all;
                // 获取动态表格数据
                routerConfig = getWrapperRouterData(app || getDvaApp());
                routerData = {};
                Object.keys(routerConfig).forEach(function (path) {
                  var pathRegexp = pathToRegexp(path);
                  var router = routerConfig[path];
                  router = _objectSpread(_objectSpread({}, router), {}, {
                    name: router.name,
                    // tab 用到的数据
                    pathRegexp: pathRegexp,
                    title: router.title,
                    icon: router.icon,
                    closable: _isBoolean(router.closable) ? router.closable : true,
                    path: path,
                    // tab 用到的数据
                    authority: router.authority
                  });
                  routerData[path] = router;
                }); // 加载国际化
                // 第一次加载肯定是没有切换语言的

                localLangCache[language] = {};
                promiseAllLocale = [call(queryPromptLocale, organizationId, language, 'cpaas.common')];
                _context18.next = 9;
                return all(promiseAllLocale);

              case 9:
                _yield$all11 = _context18.sent;
                _yield$all12 = _slicedToArray(_yield$all11, 1);
                promptLocale = _yield$all12[0];
                safePromptLocale = getResponse(promptLocale); // 设置或切换 当前intl的语言

                loadLocales = intl && intl.options && intl.options.locales || {};
                intl.init({
                  currentLocale: language,
                  locales: loadLocales,
                  warningHandler: function
                    /* e */
                  warningHandler() {// todo
                    // console.warn(e);
                  }
                });
                intl.load(_defineProperty({}, language, safePromptLocale));
                _context18.next = 18;
                return put({
                  type: 'loadUILocale',
                  payload: {
                    language: language
                  }
                });

              case 18:
                _context18.next = 20;
                return put({
                  type: 'updateState',
                  payload: {
                    routerData: routerData,
                    language: language,
                    // TabListen 监听
                    menuLoad: true,
                    tabsIsInit: true
                  }
                });

              case 20:
              case "end":
                return _context18.stop();
            }
          }
        }, privateLazyInit);
      }),

      /**
       * 首屏 预加载内容
       * 初始化语言和菜单数据
       */
      baseInit: /*#__PURE__*/_regeneratorRuntime.mark(function baseInit(_ref37, _ref38) {
        var _ref37$payload, _ref37$payload$langua, language, organizationId, call, put, all, promiseAllLocale, _yield$all13, _yield$all14, promptLocale, safePromptLocale, loadLocales;

        return _regeneratorRuntime.wrap(function baseInit$(_context19) {
          while (1) {
            switch (_context19.prev = _context19.next) {
              case 0:
                _ref37$payload = _ref37.payload, _ref37$payload$langua = _ref37$payload.language, language = _ref37$payload$langua === void 0 ? 'dict' : _ref37$payload$langua, organizationId = _ref37$payload.organizationId;
                call = _ref38.call, put = _ref38.put, all = _ref38.all;
                // 第一次加载肯定是没有切换语言的
                localLangCache[language] = {};
                promiseAllLocale = [call(queryPromptLocale, organizationId, language, 'cpaas.common')];
                _context19.next = 6;
                return all(promiseAllLocale);

              case 6:
                _yield$all13 = _context19.sent;
                _yield$all14 = _slicedToArray(_yield$all13, 1);
                promptLocale = _yield$all14[0];
                safePromptLocale = getResponse(promptLocale); // 设置或切换 当前intl的语言

                loadLocales = intl && intl.options && intl.options.locales || {};
                intl.init({
                  currentLocale: language,
                  locales: loadLocales,
                  warningHandler: function
                    /* e */
                  warningHandler() {// todo
                    // console.warn(e);
                  }
                });
                intl.load(_defineProperty({}, language, safePromptLocale)); // 初始化 menuTabs

                _context19.next = 15;
                return put({
                  type: 'initMenuTabs'
                });

              case 15:
                // tab 初始化完成后才进入 menuTab 处理流程
                tabListen();
                _context19.next = 18;
                return put({
                  type: 'loadUILocale',
                  payload: {
                    language: language
                  }
                });

              case 18:
              case "end":
                return _context19.stop();
            }
          }
        }, baseInit);
      }),
      baseLazyInit: /*#__PURE__*/_regeneratorRuntime.mark(function baseLazyInit(_ref39, _ref40) {
        var _ref39$payload$langua, language, call, put, all, list, menuListReq, _yield$all15, _yield$all16, menuListRes, menuList, menus, menuLocaleIntl, menuData, routerConfig, routerData, queryMenus;

        return _regeneratorRuntime.wrap(function baseLazyInit$(_context20) {
          while (1) {
            switch (_context20.prev = _context20.next) {
              case 0:
                _ref39$payload$langua = _ref39.payload.language, language = _ref39$payload$langua === void 0 ? 'dict' : _ref39$payload$langua;
                call = _ref40.call, put = _ref40.put, all = _ref40.all;
                list = [];
                menuListReq = call(queryMenu, {
                  lang: language
                }); // 获取动态表格数据

                _context20.next = 6;
                return all([menuListReq]);

              case 6:
                _yield$all15 = _context20.sent;
                _yield$all16 = _slicedToArray(_yield$all15, 1);
                menuListRes = _yield$all16[0];
                menuList = getResponse(menuListRes); // TODO: 接口完成后 通过菜单来获取 菜单的国际化
                // const menuLocale = {};

                parseMenuData(list, null, menuList || []);
                menus = list;
                menuLocaleIntl = {};
                parseMenuToLocaleIntl(menuList, menuLocaleIntl);
                menuData = getFlatMenuData(menus);
                intl.load(_defineProperty({}, language, menuLocaleIntl));
                routerConfig = getWrapperRouterData(app || getDvaApp());
                routerData = {}; // The route matches the menu

                Object.keys(routerConfig).forEach(function (path) {
                  // Regular match item name
                  // eg.  router /user/:id === /user/chen
                  var pathRegexp = pathToRegexp(path);
                  var menuKey = Object.keys(menuData).find(function (key) {
                    return pathRegexp.test("".concat(key));
                  });
                  var menuItem = {}; // If menuKey is not empty

                  if (menuKey) {
                    menuItem = menuData[menuKey];
                  }

                  var router = routerConfig[path]; // If you need to configure complex parameter routing,
                  // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
                  // eg . /list/:type/user/info/:id

                  router = _objectSpread(_objectSpread({}, router), {}, {
                    name: router.name || menuItem.name,
                    // tab 用到的数据
                    pathRegexp: pathRegexp,
                    title: router.title || menuItem.name,
                    icon: router.icon || menuItem.icon,
                    closable: _isBoolean(router.closable) ? router.closable : true,
                    path: path,
                    // tab 用到的数据
                    authority: router.authority || menuItem.authority,
                    hideInBreadcrumb: router.hideInBreadcrumb || menuItem.hideInBreadcrumb
                  });
                  routerData[path] = router;
                });
                queryMenus = getMenuNodeList(menus, []);
                _context20.next = 22;
                return put({
                  type: 'updateState',
                  payload: {
                    routerData: routerData,
                    language: language,
                    menu: menus,
                    menuLeafNode: queryMenus,
                    // 菜单加载完毕
                    menuLoad: true // lowCodeMenuDataRes,

                  }
                });

              case 22:
              case "end":
                return _context20.stop();
            }
          }
        }, baseLazyInit);
      }),
      // 获取 trace 状态
      getTraceStatus: /*#__PURE__*/_regeneratorRuntime.mark(function getTraceStatus(_, _ref41) {
        var call, put, res;
        return _regeneratorRuntime.wrap(function getTraceStatus$(_context21) {
          while (1) {
            switch (_context21.prev = _context21.next) {
              case 0:
                call = _ref41.call, put = _ref41.put;
                _context21.t0 = getResponse;
                _context21.next = 4;
                return call(_getTraceStatus);

              case 4:
                _context21.t1 = _context21.sent;
                res = (0, _context21.t0)(_context21.t1);

                if (!res) {
                  _context21.next = 9;
                  break;
                }

                _context21.next = 9;
                return put({
                  type: 'updateState',
                  payload: {
                    traceStatus: res
                  }
                });

              case 9:
                return _context21.abrupt("return", res);

              case 10:
              case "end":
                return _context21.stop();
            }
          }
        }, getTraceStatus);
      }),
      // trace 相关
      startTrace: /*#__PURE__*/_regeneratorRuntime.mark(function startTrace(_, _ref42) {
        var call;
        return _regeneratorRuntime.wrap(function startTrace$(_context22) {
          while (1) {
            switch (_context22.prev = _context22.next) {
              case 0:
                call = _ref42.call;
                _context22.t0 = getResponse;
                _context22.next = 4;
                return call(_startTrace);

              case 4:
                _context22.t1 = _context22.sent;
                return _context22.abrupt("return", (0, _context22.t0)(_context22.t1));

              case 6:
              case "end":
                return _context22.stop();
            }
          }
        }, startTrace);
      }),
      endTrace: /*#__PURE__*/_regeneratorRuntime.mark(function endTrace(_, _ref43) {
        var call, put, res;
        return _regeneratorRuntime.wrap(function endTrace$(_context23) {
          while (1) {
            switch (_context23.prev = _context23.next) {
              case 0:
                call = _ref43.call, put = _ref43.put;
                _context23.t0 = getResponse;
                _context23.next = 4;
                return call(_endTrace);

              case 4:
                _context23.t1 = _context23.sent;
                res = (0, _context23.t0)(_context23.t1);

                if (!res) {
                  _context23.next = 9;
                  break;
                }

                _context23.next = 9;
                return put({
                  type: 'updateState',
                  payload: {
                    traceLogInfo: res
                  }
                });

              case 9:
                return _context23.abrupt("return", res);

              case 10:
              case "end":
                return _context23.stop();
            }
          }
        }, endTrace);
      })
    },
    reducers: {
      updateState: function updateState(state, _ref44) {
        var payload = _ref44.payload;
        return _objectSpread(_objectSpread({}, state), payload);
      },
      changeLayoutCollapsed: function changeLayoutCollapsed(state, _ref45) {
        var payload = _ref45.payload;
        return _objectSpread(_objectSpread({}, state), {}, {
          collapsed: payload
        });
      },
      saveNotices: function saveNotices(state, _ref46) {
        var payload = _ref46.payload;
        return _objectSpread(_objectSpread({}, state), payload);
      },
      saveAnnounces: function saveAnnounces(state, _ref47) {
        var payload = _ref47.payload;
        return _objectSpread(_objectSpread({}, state), payload);
      },
      saveClearedNotices: function saveClearedNotices(state, _ref48) {
        var payload = _ref48.payload;
        return _objectSpread(_objectSpread({}, state), {}, {
          notices: state.notices.filter(function (item) {
            return item.type !== payload;
          })
        });
      },
      addTab: function addTab(state, _ref49) {
        var payload = _ref49.payload;
        var newTab = payload.newTab;
        var tabs = state.tabs;
        var activeTabMenuId = getActiveTabMenuId(newTab.key);
        return _objectSpread(_objectSpread({}, state), {}, {
          activeTabKey: newTab.key,
          activeTabMenuId: activeTabMenuId.id,
          tabs: [].concat(_toConsumableArray(tabs), [newTab])
        });
      },

      /**
       * 使用新的 tab 替换掉原先的tab
       * @param {Object} state - 之前的state
       * @param {Object} payload
       * @param {Object} payload.tab 需要被替换的tab
       * @param {String!} payload.tab.key 需要被替换的tab的key
       * @param {Object!} payload.newTab 新的tab
       */
      replaceTab: function replaceTab(state, _ref50) {
        var payload = _ref50.payload;
        var tab = payload.tab,
            newTab = payload.newTab;
        var tabs = state.tabs;

        var newTabs = _map(tabs, function (lTab) {
          if (lTab.key === tab.key) {
            return newTab;
          }

          return lTab;
        });

        var activeTabMenuId = getActiveTabMenuId(newTab.key);
        return _objectSpread(_objectSpread({}, state), {}, {
          activeTabKey: newTab.key,
          activeTabMenuId: activeTabMenuId.id,
          tabs: newTabs
        });
      },

      /**
       *
       * 更新 tabs 中对应key的tab, 不激活更新的tab
       * @param {Object} state - 之前的state
       * @param {Object} updateTab - 更新的 tab patch
       * @param {Object} updateTab.key - 更新的 tab 的key
       * @returns {{activeTabKey: *, tabs: *}}
       */
      updateTab: function updateTab(state, _ref51) {
        var updateTab = _ref51.payload;
        var tabs = state.tabs;

        var newTabs = _map(tabs, function (lTab) {
          if (lTab.key === updateTab.key) {
            return _objectSpread(_objectSpread({}, lTab), updateTab);
          }

          return lTab;
        });

        return _objectSpread(_objectSpread({}, state), {}, {
          tabs: newTabs
        });
      },
      cleanTabs: function cleanTabs(state) {
        var activeTabMenuId = getActiveTabMenuId(getInitialActiveTabKey());
        return _objectSpread(_objectSpread({}, state), {}, {
          tabs: getInitialTabData(),
          activeTabKey: getInitialActiveTabKey(),
          activeTabMenuId: activeTabMenuId.id
        });
      },
      updateMenuLeafNode: function updateMenuLeafNode(state) {
        return _objectSpread(_objectSpread({}, state), {}, {
          menuLeafNode: state.menuLeafNode.map(function (menu) {
            return _objectSpread(_objectSpread({}, menu), {}, {
              title: menu.name && intl.get(menu.name).d(menu.name)
            });
          })
        });
      },
      // 初始化 menuTabs
      initMenuTabs: function initMenuTabs(state) {
        var tabs = getInitialTabData();
        var activeTabKey = getInitialActiveTabKey();
        return _objectSpread(_objectSpread({}, state), {}, {
          activeTabKey: state.tabsIsInit ? state.activeTabKey : activeTabKey,
          tabs: state.tabsIsInit ? state.tabs : tabs,
          tabsIsInit: true
        });
      },
      // 初始化 menuTabs
      initActiveTabMenuId: function initActiveTabMenuId(state) {
        var activeTabMenuId = getActiveTabMenuId(getInitialActiveTabKey());
        return _objectSpread(_objectSpread({}, state), {}, {
          activeTabMenuId: activeTabMenuId.id
        });
      },
      hideLayoutPageLoading: function hideLayoutPageLoading(state) {
        return _objectSpread(_objectSpread({}, state), {}, {
          layoutLoading: false
        });
      },
      showLayoutPageLoading: function showLayoutPageLoading(state) {
        return _objectSpread(_objectSpread({}, state), {}, {
          layoutLoading: true
        });
      }
    },
    subscriptions: {
      setup: function setup(_ref52) {
        var history = _ref52.history;
        // Subscribe history(url) change, trigger `load` action if pathname is `/`
        var unListen = history.listen(function (_ref53) {
          var pathname = _ref53.pathname;
          tabListen(pathname);
        });
        return function () {
          unListen();
          persistMenuTabs();
        };
      }
    }
  };
}

export { getGlobalModalConfig };
export default getGlobalModalConfig({
  getWrapperRouterData: getRouterData
});